import React, { useState, useEffect } from 'react';
import { Upload, Button, message, List, Card } from 'antd';
import { UploadOutlined, FileTextOutlined } from '@ant-design/icons';
import { addDocument, getDocuments } from '../services/api';

const KnowledgeManagement: React.FC = () => {
  const [file, setFile] = useState<File | null>(null);
  const [loading, setLoading] = useState(false);
  const [documents, setDocuments] = useState<string[]>([]);
  const [documentsLoading, setDocumentsLoading] = useState(false);

  // 加载已嵌入的文档列表
  useEffect(() => {
    loadDocuments();
  }, []);

  const loadDocuments = async () => {
    setDocumentsLoading(true);
    try {
      const data = await getDocuments();
      setDocuments(data.documents || []);
    } catch (error) {
      console.error('Error loading documents:', error);
      message.error('加载文档列表失败');
    } finally {
      setDocumentsLoading(false);
    }
  };

  const handleUpload = async () => {
    if (!file) {
      message.warning('请选择文件');
      return;
    }
    
    // 检查文件大小（10MB限制）
    const maxSize = 10 * 1024 * 1024; // 10MB
    if (file.size > maxSize) {
      message.error(`文件大小超过限制，请选择小于10MB的文件。当前文件大小：${(file.size / (1024 * 1024)).toFixed(2)}MB`);
      return;
    }
    
    setLoading(true);
    try {
      await addDocument(file);
      message.success('文档添加成功');
      setFile(null);
      // 重新加载文档列表
      loadDocuments();
    } catch (error) {
      message.error('文档添加失败');
    } finally {
      setLoading(false);
    }
  };

  const beforeUpload = (file: File) => {
    // 检查文件格式
    const supportedFormats = ['.pdf', '.doc', '.docx', '.xls', '.xlsx', '.txt'];
    const fileExtension = file.name.toLowerCase().substring(file.name.lastIndexOf('.'));
    
    if (!supportedFormats.includes(fileExtension)) {
      message.error(`不支持的文件格式：${fileExtension}，请上传PDF、Word、Excel或TXT文件`);
      return false;
    }
    
    setFile(file);
    return false;
  };

  return (
    <div style={{ padding: '20px', maxWidth: '800px', margin: '0 auto' }}>
      <Card title="上传文档" style={{ marginBottom: '20px' }}>
        <Upload beforeUpload={beforeUpload} showUploadList={false}>
          <Button icon={<UploadOutlined />}>选择文件</Button>
        </Upload>
        {file && (
          <div style={{ marginTop: '10px' }}>
            <span>{file.name}</span>
            <Button
              type="primary"
              onClick={handleUpload}
              loading={loading}
              style={{ marginLeft: '10px' }}
            >
              上传
            </Button>
          </div>
        )}
      </Card>

      <Card title={`已嵌入的文档 (${documents.length} 个)`}>
        <List
          loading={documentsLoading}
          dataSource={documents}
          renderItem={(docName) => (
            <List.Item>
              <List.Item.Meta
                avatar={<FileTextOutlined style={{ fontSize: '18px', color: '#1890ff' }} />}
                title={docName}
              />
            </List.Item>
          )}
          locale={{ emptyText: '暂无已嵌入的文档' }}
        />
      </Card>
    </div>
  );
};

export default KnowledgeManagement;
